<template>
  <div class="major-search-main">
    <div class="main-wrapper">
      <div class="main-wrapper-left">
        <div class="header-tabs">
          <div class="tabs-list">
            <div
              class="tab-item"
              :class="{ active: currentTab.id == item.id }"
              v-for="item in industryList"
              @click="handleChangeTab(item)"
            >
              {{ item.industryName }}
            </div>
          </div>
          <div class="reset-box" @click="handleResetChecked">
            <img src="@/assets/images/industryMap/reset.png" alt="" />
            重置
          </div>
        </div>
        <div class="second-industry">
          <ul>
            <li
              v-for="item in currentTab.child"
              :class="{ active: item.checked }"
              @click="handleChecked(item)"
            >
              <span>{{ item.industryName }}</span>
              <img
                class="checked-img"
                :src="item.checked ? checkedImg : unCheckedImg"
                alt=""
              />
            </li>
          </ul>
        </div>
      </div>
      <div class="industry-list-container">
        <Autocomplete></Autocomplete>
        <div class="industry-list scroll-list" @scroll="handleScroll">
          <template v-for="item in showIndustryData" :key="item.id">
            <IndustryItem :item="item"></IndustryItem>
          </template>
          <van-loading
            v-if="loading && !finished"
            type="spinner"
            color="#0b6eff"
            size="36px"
          />
          <div
            class="empty-container"
            v-if="!showIndustryData.length && finished"
          >
            <NotData :text="'暂无相关产业'" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, onActivated } from 'vue';
import { getIndustryTreeReq } from '@/api/industryMap.js';
import antiShake from '@/utils/antiShake.js'; // 引入防抖函数
import IndustryItem from '@/views/industryMap/industryHome/components/IndustryItem.vue';
import NotData from '@/views/industryMap/components/NotData.vue';
import Autocomplete from '@/views/industryMap/industryHome/components/Autocomplete.vue';
import checkedImg from '@/assets/images/industryMap/checked.png';
import unCheckedImg from '@/assets/images/industryMap/unChecked.png';

const showIndustryData = ref([]);
const pageNum = ref(1);
const pageSize = ref(12);
const finished = ref(false);
const currentTab = ref('');
const flatIndustryList = ref([]);
const industryList = ref([]);
const loading = ref(false);
// 获取完整产业
const getIndustryTree = async () => {
  const params = {
    industryType: 10,
    extend: '',
  };
  const res = await getIndustryTreeReq(params);
  let data = JSON.parse(JSON.stringify(res.data)) || [];
  // 暂时只需要战略新兴产业+国标行业
  data = data.filter((item) => item.id == 5 || item.id == 2107);
  industryList.value = data;
  handleChangeTab(data[0]); //默认选中第一个产业
};
// 数据扁平化
const flattenIndustryData = (data) => {
  return data.flatMap((topItem) =>
    topItem.child.flatMap((secondItem) => [
      { ...secondItem }, // 第二层级（保留所有字段）
      // 第三层级（保留所有字段）
      ...(secondItem.child?.map((thirdItem) => ({
        ...thirdItem,
      })) || []),
    ])
  );
};
// 滚动监听
const handleScroll = antiShake(() => {
  const listElement = document.querySelector('.scroll-list');
  if (listElement) {
    const { scrollTop, scrollHeight, clientHeight } = listElement;
    if (scrollTop + clientHeight >= scrollHeight - 10 && !finished.value) {
      handleSliceData();
    }
  }
}, 300);
// 数据切割，一次加载12条数据
const handleSliceData = () => {
  loading.value = true;
  showIndustryData.value = showIndustryData.value.concat(
    flatIndustryList.value.slice(
      (pageNum.value - 1) * pageSize.value,
      pageNum.value * pageSize.value
    )
  );
  pageNum.value++;
  if (showIndustryData.value.length >= flatIndustryList.value.length) {
    finished.value = true;
  }
  loading.value = false;
};
// 切换tab
const handleChangeTab = (val) => {
  val.checked = false;
  if (val.child && val.child.length) {
    val.child.forEach((item) => {
      item.checked = false;
    });
  }
  currentTab.value = val;
  reset();
  flatIndustryList.value = flattenIndustryData([currentTab.value]);
  handleSliceData();
  document.querySelector('.second-industry').scrollTop = 0;
  document.querySelector('.scroll-list').scrollTop = 0;
};
/**
 * 点击产业
 * @param val
 * [{ child }] 构建三级菜单结构
 */
const handleChecked = (val) => {
  val.checked = !val.checked;
  const child = currentTab.value.child?.filter((item) => item.checked);
  reset();
  flatIndustryList.value = flattenIndustryData(
    child.length ? [{ child }] : industryList.value
  );
  handleSliceData();
};
// 重置选中
const handleResetChecked = () => {
  currentTab.value.child?.forEach((item) => {
    item.checked = false;
  });
  reset();
  flatIndustryList.value = flattenIndustryData([currentTab.value]);
  handleSliceData();
  document.querySelector('.scroll-list').scrollTop = 0;
};

// 重置状态
const reset = () => {
  pageNum.value = 1;
  showIndustryData.value = [];
  flatIndustryList.value = [];
  finished.value = false;
};
onActivated(() => {
  reset();
  getIndustryTree();
});
</script>
<style lang="scss" scoped>
.major-search-main {
  height: 100%;
  padding: 0 60px 32px;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  .main-wrapper {
    width: 100%;
    height: 100%;
    padding: 32px 0 32px 60px;
    background: #eff9ff;
    border-radius: 38px;
    display: flex;
    flex-direction: row;
    box-sizing: border-box;
  }
}
.main-wrapper-left {
  width: 484px;
  background: #ffffff;
  box-shadow: 0px 2px 28px 6px rgba(184, 200, 219, 0.04);
  border-radius: 20px;
  display: flex;
  flex-direction: column;
  .header-tabs {
    padding: 32px 28px 28px;
    display: flex;
    align-items: center;
    .tabs-list {
      flex: 1;
      display: flex;
      font-weight: bold;
      font-size: 26px;
      color: #7f7f7f;
      overflow-x: auto;
      .tab-item {
        margin-right: 40px;
        padding: 8px 0;
        flex-shrink: 0;
        &.active {
          color: #222222;
          position: relative;
          &::after {
            content: '';
            position: absolute;
            height: 4px;
            width: 32px;
            left: 50%;
            transform: translateX(-50%);
            bottom: 0;
            background: #0b6eff;
            border-radius: 3px;
          }
        }
      }
    }
    .reset-box {
      margin-left: 24px;
      font-size: 24px;
      color: #999999;
      display: flex;
      align-items: center;
      img {
        width: 28px;
        height: 28px;
        margin-right: 6px;
      }
    }
  }
  .second-industry {
    flex: 1;
    padding: 0 28px;
    overflow-y: auto;
    ul > li {
      padding: 0 28px;
      height: 78px;
      font-weight: 400;
      font-size: 24px;
      color: #666666;
      display: flex;
      justify-content: space-between;
      align-items: center;
      span {
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
      }
      img {
        width: 28px;
        height: 28px;
      }
      &.active {
        font-weight: bold;
        color: #0b6eff;
        background: #eff5ff;
      }
    }
  }
}
.industry-list-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  .industry-list {
    flex: 1;
    height: 100%;
    padding: 12px 42px 16px 60px;
    overflow: hidden;
    overflow-y: auto;
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-template-rows: 195px 195px 195px;
    grid-gap: 32px 22px;
    box-sizing: border-box;
    .industry-item {
      height: 195px;
    }
  }
}
.van-loading {
  grid-column-start: span 3;
  text-align: center;
}
.empty-container {
  grid-column-start: span 3;
  grid-row-start: span 3;
}

.tabs-list {
  &::-webkit-scrollbar {
    display: none;
  }
}
</style>
